package com.free.explayer.player;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;

import com.free.explayer.Mlog;
import com.free.explayer.files.FileHelper;

import java.io.IOException;



public class MusicPlayer {

    private static final String TAG = "MusicPlayer";
    private Context mContext;
    private MediaPlayer mMediaPlayer;
    private FileHelper mFileHelper;
    private OnPlayPositionChangeListener mListener;
    private Handler mHandler;

    public MusicPlayer(Context context) {
        mContext = context;
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void init() {
        mMediaPlayer = new MediaPlayer();
        mFileHelper = new FileHelper(mContext);
    }

    public void prepare() {
        try {
            String path = mFileHelper.firstMusic();
            Mlog.i(TAG, "path:%s", path);
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play() {
        Mlog.i(TAG, "play, isPlaying:%s", isPlaying());
        if (!isPlaying()) {
            mMediaPlayer.start();
            updatePosition();
        }
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public void pause() {
        Mlog.i(TAG, "pause, isPlaying:%s", isPlaying());
        if (isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    public void stop() {
        mMediaPlayer.stop();
    }

    public void seekTo(int progress) {
        mMediaPlayer.seekTo(progress);
    }

    public void setOnPlayPositionChangeListener(OnPlayPositionChangeListener listener) {
        mListener = listener;
        updatePosition();
    }

    private void updatePosition() {

        if (isPlaying() && mListener != null) {
            mHandler.post(unpdatePositionRunnable);
        }
    }

    private final Runnable unpdatePositionRunnable = new Runnable() {
        @Override
        public void run() {
            int position = mMediaPlayer.getCurrentPosition();
            if (mListener != null) {
                mListener.onChange(position, mMediaPlayer.getDuration());
            }
            mHandler.postDelayed(this, 100L);
        }
    };

    public int getDuration() {
        return mMediaPlayer.getDuration();
    }
}
